// 区块链类型定义
export enum ChainType {
  ETHEREUM = 'ethereum',
  BITCOIN = 'bitcoin',
  BSC = 'bsc',
  POLYGON = 'polygon',
  BASE = 'base',
  SOLANA = 'solana'
}

// 交易数据结构
export interface Transaction {
  id: string;
  hash: string;
  chain: ChainType;
  fromAddress: string; // 修正字段名
  toAddress: string;   // 修正字段名
  value: string; // 原始数值（ETH、BTC等）
  valueUsd: number; // 修正字段名：美元价值
  blockNumber: number;
  blockHash?: string; // 新增字段
  transactionIndex?: number; // 新增字段
  timestamp: Date;
  gasPrice?: string | undefined;
  gasUsed?: number | undefined;
  
  // 代币相关字段
  tokenAddress?: string | undefined;
  tokenSymbol?: string | undefined;
  tokenDecimals?: number | undefined;
  confirmed?: boolean; // 改为可选，因为schema中没有这个字段
  
  // 地址标签字段 - 修正为简单字符串格式以匹配数据库
  fromLabel?: string | undefined;
  toLabel?: string | undefined;
}

// 地址标签
export interface AddressLabel {
  address: string;
  label: string;
  type: 'exchange' | 'whale' | 'defi' | 'bridge' | 'other';
  chain: ChainType;
  createdAt: Date;
}

// 监控配置
export interface MonitorConfig {
  id: string;
  chain: ChainType;
  enabled: boolean;
  minValue: number; // 最小监控金额(USD)
  includeTokens: boolean;
  tokenWhitelist?: string[] | undefined; // 监控的代币地址白名单
  excludeAddresses?: string[] | undefined; // 排除的地址
  alertChannels: AlertChannel[];
  createdAt: Date;
  updatedAt: Date;
}

// 告警渠道
export interface AlertChannel {
  id: string;
  type: 'email' | 'webhook' | 'telegram' | 'slack';
  config: AlertChannelConfig;
  enabled: boolean;
}

export type AlertChannelConfig = {
  email?: {
    to: string[];
    subject?: string | undefined;
  } | undefined;
  webhook?: {
    url: string;
    headers?: Record<string, string> | undefined;
  } | undefined;
  telegram?: {
    botToken: string;
    chatId: string;
  } | undefined;
  slack?: {
    webhookUrl: string;
    channel?: string | undefined;
  } | undefined;
};

// 告警消息
export interface AlertMessage {
  id: string;
  transaction: Transaction;
  configId: string;
  channels: string[];
  sent: boolean;
  sentAt?: Date | undefined;
  error?: string | undefined;
  createdAt: Date;
}

// API响应格式
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T | undefined;
  error?: string | undefined;
  message?: string | undefined;
  timestamp: string;
}

// 分页参数
export interface PaginationParams {
  page: number;
  limit: number;
  sortBy?: string | undefined;
  sortOrder?: 'asc' | 'desc' | undefined;
}

// 分页响应
export interface PaginatedResponse<T> {
  items: T[];
  total: number;
  page: number;
  limit: number;
  totalPages: number;
}

// WebSocket消息类型
export interface WebSocketMessage {
  type: 'transaction' | 'alert' | 'status' | 'error';
  data: any;
  timestamp: string;
}

// 统计数据
export interface Statistics {
  totalTransactions: number;
  totalValueUSD: number;
  transactionsByChain: Record<ChainType, number>;
  valueByChain: Record<ChainType, number>;
  topAddresses: Array<{
    address: string;
    label?: string | undefined;
    transactionCount: number;
    totalValueUSD: number;
  }>;
  recentTransactions: Transaction[];
  alertsToday: number;
}

// 数据库连接配置
export interface DatabaseConfig {
  host: string;
  port: number;
  database: string;
  username: string;
  password: string;
  ssl?: boolean | undefined;
}

// Redis配置
export interface RedisConfig {
  host: string;
  port: number;
  password?: string | undefined;
  db?: number | undefined;
}

// 区块链RPC配置
export interface ChainConfig {
  rpcUrl: string;
  wssUrl?: string | undefined;
  apiKey?: string | undefined;
  scanApiKey?: string | undefined;
  confirmations: number;
}

// 应用配置
export interface AppConfig {
  port: number;
  nodeEnv: string;
  database: DatabaseConfig;
  redis: RedisConfig;
  chains: Record<ChainType, ChainConfig>;
  monitoring: {
    defaultMinValue: number;
    maxTransactionsPerBlock: number;
    blockCheckInterval: number;
  };
  alerts: {
    email: {
      enabled: boolean;
      host: string;
      port: number;
      user: string;
      password: string;
    };
    webhook: {
      enabled: boolean;
      defaultUrl?: string | undefined;
    };
  };
  logging: {
    level: string;
    file: string;
  };
} 

// ===== 分析系统相关类型定义 =====

// 实体信息
export interface EntityInfo {
  id: string;
  name: string;
  type: 'individual' | 'institution' | 'exchange' | 'defi_protocol' | 'unknown';
  addresses: string[];
  chains: ChainType[];
  riskScore: number; // 0-100
  confidence: number; // 0-1
  lastUpdated: Date;
  metadata?: Record<string, any>;
}

// Address Profile
export interface AddressProfile {
  address: string;
  chain: ChainType;
  entityId?: string | undefined;
  labels: AddressLabel[];
  riskScore: number;
  transactionCount: number;
  totalVolumeUSD: number;
  firstSeen: Date;
  lastActive: Date;
  patterns: TransactionPattern[];
  associations: AddressAssociation[];
}

// 地址关联
export interface AddressAssociation {
  relatedAddress: string;
  relationshipType: 'funding' | 'recipient' | 'cluster' | 'similar_pattern';
  strength: number; // 0-1
  evidence: string[];
  firstSeen: Date;
}

// 交易模式
export interface TransactionPattern {
  id: string;
  type: 'deposit' | 'withdrawal' | 'defi_interaction' | 'arbitrage' | 'accumulation' | 'distribution' | 'anomaly';
  confidence: number;
  description: string;
  frequency: number;
  avgAmount: number;
  timePattern?: {
    dayOfWeek?: number[];
    hourOfDay?: number[];
    isRegular: boolean;
  };
  relatedAddresses: string[];
  detectedAt: Date;
}

// 行为洞察
export interface BehaviorInsight {
  id: string;
  address: string;
  type: 'whale_activity' | 'exchange_flow' | 'defi_farming' | 'cross_chain' | 'suspicious';
  title: string;
  description: string;
  severity: 'low' | 'medium' | 'high' | 'critical';
  confidence: number;
  evidence: Evidence[];
  timestamp: Date;
  impact?: {
    marketImpact: 'negligible' | 'minor' | 'moderate' | 'major';
    priceImpact?: number;
    volumeImpact?: number;
  };
}

// 证据
export interface Evidence {
  type: 'transaction' | 'pattern' | 'timing' | 'amount' | 'address_relationship';
  description: string;
  data: any;
  weight: number; // 0-1
}

// 异常告警
export interface AnomalyAlert {
  id: string;
  address: string;
  type: 'unusual_volume' | 'new_pattern' | 'suspicious_timing' | 'risk_escalation';
  severity: 'low' | 'medium' | 'high' | 'critical';
  title: string;
  description: string;
  detectedAt: Date;
  threshold: number;
  actualValue: number;
  historicalBaseline: number;
  recommendations: string[];
}

// 市场影响分析
export interface MarketImpact {
  transactionId: string;
  asset: string;
  chain: ChainType;
  liquidityImpact: {
    immediateImpact: number; // 即时价格影响百分比
    expectedRecoveryTime: number; // 预期恢复时间（分钟）
    affectedPools: string[];
  };
  sentimentImpact: {
    socialMentions: number;
    sentimentScore: number; // -1 to 1
    trendingStatus: boolean;
  };
  historicalComparison: {
    similarTransactions: number;
    avgMarketReaction: number;
    recoveryPattern: string;
  };
  predictions: PricePrediction[];
}

// 价格预测
export interface PricePrediction {
  timeframe: '1h' | '4h' | '24h' | '7d';
  expectedChange: number; // 百分比
  confidence: number; // 0-1
  factors: string[];
  riskFactors: string[];
}

// 情报报告
export interface IntelligenceReport {
  id: string;
  title: string;
  summary: string;
  type: 'transaction_analysis' | 'pattern_discovery' | 'market_intelligence' | 'risk_assessment';
  insights: Insight[];
  recommendations: Recommendation[];
  dataPoints: DataPoint[];
  generatedAt: Date;
  confidence: number;
  tags: string[];
}

// 洞察
export interface Insight {
  id: string;
  type: 'trend' | 'anomaly' | 'opportunity' | 'risk' | 'correlation';
  title: string;
  description: string;
  impact: 'low' | 'medium' | 'high';
  confidence: number;
  supportingData: any[];
}

// 建议
export interface Recommendation {
  id: string;
  type: 'action' | 'monitoring' | 'investigation' | 'alert_tuning';
  priority: 'low' | 'medium' | 'high' | 'urgent';
  title: string;
  description: string;
  actionItems: string[];
  expectedOutcome: string;
}

// 数据点
export interface DataPoint {
  metric: string;
  value: number | string;
  unit?: string;
  trend?: 'up' | 'down' | 'stable';
  change?: number;
  timeframe?: string;
}

// 实体关系图节点
export interface EntityNode {
  id: string;
  label: string;
  type: 'address' | 'entity' | 'transaction' | 'contract';
  chain?: ChainType;
  riskScore?: number;
  metadata: Record<string, any>;
}

// 实体关系图边
export interface EntityEdge {
  id: string;
  source: string;
  target: string;
  type: 'funding' | 'control' | 'interaction' | 'similarity';
  weight: number;
  amount?: number;
  frequency?: number;
  metadata: Record<string, any>;
} 